import React, { useState } from 'react';
import './index.scss';
import { ColumnsType } from 'antd/es/table';
import {
    Button,
    Col,
    DatePicker,
    Form,
    Input,
    Modal,
    Row,
    Table,
    Space,
    message,
} from 'antd';
import { useAntdTable } from 'ahooks';
import {
    platformAddressList,
    platformAddressAdd,
    platformAddressEdit,
    platformAddressDelete,
} from '@/config/request/manage';
import { useFormModal } from '@/hooks/useFormModal';
import PlatformAddressInfo from './platformAddressInfo';

const PlatformAddress: React.FC = () => {
    const [form] = Form.useForm();
    const [isEditInfo, setIsEditInfo] = React.useState(false);
    const formModalPlatformAddressInfo = useFormModal();
    const [rowItem, setRowItem] = useState<any>();

    const classifyOption = [
        { key: 3, value: '测试平台' },
        { key: 4, value: '内部系统平台' },
        { key: 5, value: '研发工具平台' },
        { key: 6, value: '外部工具' },
    ];

    const { tableProps, search } = useAntdTable(
        async ({ pageSize, current: pageNum }) => {
            const { searchMobileUseDate } = form.getFieldsValue();
            const params = {
                ...form.getFieldsValue(),
                startTime: searchMobileUseDate?.[0]?.format(
                    'YYYY-MM-DD 00:00:00'
                ),
                endTime: searchMobileUseDate?.[1]?.format(
                    'YYYY-MM-DD 23:59:59'
                ),
                pageNum,
                pageSize,
            };
            delete params.searchMobileUseDate;
            const res = await platformAddressList(params);
            return {
                total: res.data.data?.total ?? 0,
                list: res.data.data?.list ?? [],
            };
        },
        { defaultPageSize: 10, form }
    );

    const columns: ColumnsType<any> = [
        {
            title: <span style={{}}>平台名称</span>,
            dataIndex: 'platformName',
            key: 'platformName',
            width: 20,
        },
        {
            title: <span style={{}}>平台描述</span>,
            dataIndex: 'platformDesc',
            key: 'platformDesc',
            width: 30,
        },
        {
            title: <span style={{}}>测试地址</span>,
            dataIndex: 'testEnv',
            key: 'testEnv',
            width: 20,
        },
        {
            title: <span style={{}}>预发地址</span>,
            dataIndex: 'preEnv',
            key: 'preEnv',
            width: 20,
        },
        {
            title: <span style={{}}>线上地址</span>,
            dataIndex: 'prodEnv',
            key: 'prodEnv',
            width: 20,
        },
        {
            title: <span style={{}}>图标地址</span>,
            dataIndex: 'favicon',
            key: 'favicon',
            width: 20,
        },
        {
            title: <span style={{}}>所属类型</span>,
            dataIndex: 'classifyId',
            key: 'classifyId',
            width: 10,
            render: (value: any) => {
                return classifyOption.map((item) => {
                    if (value === item.key) {
                        return item.value;
                    }
                    return '';
                });
            },
        },
        {
            title: <span style={{}}>创建时间</span>,
            dataIndex: 'createTime',
            key: 'createTime',
            width: 20,
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 15,
            render: (_: any, record: any) => {
                return (
                    <Space size="middle" className="flex-col">
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                setRowItem(record);
                                setIsEditInfo(true);
                                formModalPlatformAddressInfo.modal.open();
                            }}
                        >
                            修改
                        </Button>
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                setRowItem(record);
                                deletePlatformAddress();
                            }}
                        >
                            删除
                        </Button>
                    </Space>
                );
            },
        },
    ];

    const editPlatformAddressInfo = async () => {
        try {
            const params =
                await formModalPlatformAddressInfo.form.validateFields();

            console.log(params.demandReviewDate);

            const response = isEditInfo
                ? await platformAddressEdit({
                      ...rowItem,
                      ...params,
                  })
                : await platformAddressAdd(params);
            if (response.data.code === 200) {
                message.success('保存成功！');
                formModalPlatformAddressInfo.modal.close();
                search.submit();
            }
        } catch (error: any) {
            // message.error(error);
            console.error('必填项未填：', error);
        }
    };

    const deletePlatformAddress = async () => {
        try {
            const response = await platformAddressDelete(rowItem);
            if (response.data.code === 200) {
                message.success('删除成功！');
                search.submit();
            }
        } catch (error: any) {
            // message.error(error);
            console.error('删除失败：', error);
        }
    };

    return (
        <div className="bg-white p-2.5">
            <Form form={form} name="supplierList_search">
                <Row>
                    <Col span={4}>
                        <Form.Item label="平台名称" name="platformName">
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="创建时间" name="searchMobileUseDate">
                            <DatePicker.RangePicker
                                placeholder={['开始日期', '结束日期']}
                                style={{ width: '100%' }}
                            />
                        </Form.Item>
                    </Col>
                    <Col span={24} style={{ textAlign: 'right' }}>
                        <Form.Item>
                            <Space size="small">
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    onClick={search.submit}
                                >
                                    搜索
                                </Button>
                                <Button type="primary" onClick={search.reset}>
                                    重置
                                </Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
                <div style={{ textAlign: 'left', marginBottom: 16 }}>
                    <Button
                        type="primary"
                        className="mt-5 mb-5"
                        onClick={() => {
                            setIsEditInfo(false);
                            setRowItem({});
                            formModalPlatformAddressInfo.modal.open();
                        }}
                    >
                        新增地址
                    </Button>
                </div>

                <Table
                    {...tableProps}
                    bordered
                    columns={columns}
                    pagination={{
                        ...tableProps.pagination,
                        showQuickJumper: true,
                        showTotal: (total) => `总计 ${total} `,
                    }}
                    scroll={{ x: 'calc(100vw + 1000px)' }}
                    locale={{ emptyText: '暂无数据' }}
                />
            </Form>
            <Modal
                destroyOnClose
                open={formModalPlatformAddressInfo.isOpen}
                onOk={() => editPlatformAddressInfo()}
                onCancel={() => {
                    formModalPlatformAddressInfo.modal.close();
                }}
                title={isEditInfo ? '修改地址' : '新增地址'}
                className="platformAddressInfo"
                okText="确定"
                cancelText="取消"
                maskClosable={false}
            >
                <PlatformAddressInfo
                    formModal={formModalPlatformAddressInfo}
                    rowItem={rowItem}
                />
            </Modal>
        </div>
    );
};

export default PlatformAddress;
